package com.xes.apps.ams.client.rd60n.jiecard.cn;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TCPServerConn implements NetConn {
	private Socket tcp_client;

	public TCPServerConn(Socket client) {
		tcp_client = client;

	}

	@Override
	public int SendData(byte[] data) {
		int result = 1;
		try {

			OutputStream out = tcp_client.getOutputStream();
			out.write(data);
			result = 0;

		} catch (Exception e) {
			Close();
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public byte[] RecvData(int len) {

		byte[] recv_data = new byte[len];
		int result = 1;
		try {
			do {
				tcp_client.setSoTimeout(5000);
				InputStream in = tcp_client.getInputStream();
				int l = 0;
				int tmp;
				while (len > 0) {

					tmp = in.read(recv_data, l, len);

					if (tmp <= 0) {
						break;
					}
					l += tmp;
					len -= tmp;
				}
				tcp_client.setSoTimeout(0);
				if (len != 0)
					break;

				result = 0;
			} while (false);
		} catch (Exception e) {
			Close();
			e.printStackTrace();
		}
		if (result == 0)
			return recv_data;
		else
			return null;
	}

	@Override
	public String ConnIpAddr() {
		if (null != tcp_client) {
			return tcp_client.getInetAddress().getHostName();
		}
		return "";
	}

	@Override
	public int ConnPort() {
		if (null != tcp_client) {
			return tcp_client.getPort();
		}
		return 0;
	}

	@Override
	public int Close() {
		// TODO Auto-generated method stub
		return 0;
	}

}
